package com.example.bysj_sb.controller;

import com.example.bysj_sb.domain.User;
import com.example.bysj_sb.service.ActorService;
import com.example.bysj_sb.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ActorService actorService;

    @PostMapping("/users")
    //设置权限
    @RequiresPermissions("user:post")
    public String add(@RequestParam("username") String username,
                      @RequestParam("password")String password,@RequestParam("actor_id")int actorId) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setActor(actorService.find(actorId));
        Boolean added=userService.add(user);
        if(added) {
            return "添加成功！";
        }else {
            return "添加失败！";
        }
    }
    @GetMapping("/users")
    //设置权限
    @RequiresPermissions("user:get")
    public List<User> findAll(){
        return userService.findAll();
    }

    @GetMapping("/users/{id}")
    //设置权限
    @RequiresPermissions("user:get")
    public User find(@PathVariable("id") int id){
        User user = userService.find(id);
        if(user!=null){
            return user;
        }else {
            throw new RuntimeException("未查询到 "+id+" !");
        }
    }

    @PutMapping("/users/{id}")
    //设置权限
    @RequiresPermissions("user:put")
    public String update(@PathVariable("id") int id,@RequestBody User user){
        user.setId(id);
        boolean updated = userService.update(user);
        if (updated){
            return "修改成功！";
        }else
        return "修改失败！";
    }

    @DeleteMapping("/users/{id}")
    //设置权限
    @RequiresPermissions("user:delete")
    public String deleteUserById(@PathVariable("id") int id){
        boolean deleted = userService.delete(id);
        if (deleted){
            return "删除成功！";
        }else
            return "删除失败！";
    }
}
